/**
 * Created by wushanxin on 14-4-8.
 */

var log = require("../lib/log");
var config = require('../config');
var crypto = require('crypto');
var RUtil = require('./dataformatUtil');


var db = require("../lib/db");
var viruser=require('../models/viruser.js');
var roles=require('../models/roles.js');
exports.index = function(request, response) {

    var method = request.method || '';

    if(typeof(request.session.admin)=="undefined" || request.session.admin.length==0)
    {
        response.send("<script>window.parent.location.href='login.html';</script>");
        return;
    }

    if(request.session.roleinfo.flag==0)
    {
        response.send("<script>window.parent.location.href='index.html';</script>");
        return;
    }

    var viruserdata=RUtil.viruserdata(request);
    viruserdata.retdata.nickname =request.session.admin.nickname;
    viruserdata.retdata.roleinfo = request.session.roleinfo;
    viruserdata.retdata.userinfo = request.session.admin;
    viruserdata.retdata.title="权限管理";
    if(method.toUpperCase() === "GET") {
        viruserdata.retdata.authlistemun=RUtil.authlistemun;
        viruserdata.retdata.statlistemun=RUtil.statlistemun;
        viruserdata.retdata.rolelist={};

        roles.selectAll(function(error,results) {
            if((error)!== null)
            {
                // 数据库异常
                viruserdata.retdata.info = "载入失败：系统内部错误(错误码："+error.errno+")";
                viruserdata.retdata.success=false;

                response.render("userinfo", viruserdata);

            }
            else if(results.length <= 0) {
                // 不存在，直接响应页面
                viruserdata.retdata.info = "没有任何权限分级记录!";
                viruserdata.retdata.success=false;

                response.render("userinfo", viruserdata);
            } else {
                //存在数据将数据发到页面
                viruserdata.retdata.success=true;
                for(var i = 0; i < results.length; i++)
                {
                    results[i].authnumber=RUtil.getspecialauthlist(results[i].authnumber);
                    results[i].statnumber=RUtil.getspecialstatlist(results[i].statnumber);
                }
                viruserdata.retdata.rolelist= results;



                if(request.query.oper == "add")
                {
                    viruserdata.retdata.info = "添加代理商/商户信息";
                    viruserdata.retdata.success=true;

                    response.render("userinfo.html",viruserdata);
                }
                else if(request.query.oper == "edit")
                {
                    viruser.selectByIDForUserinfo(request.query.id, function(error,results) {
                        if((error)!== null)
                        {
                            // 数据库异常
                            viruserdata.retdata.info = "载入失败：系统内部错误(错误码："+error.errno+")";
                            viruserdata.retdata.success=false;

                            response.render("userinfo", viruserdata);

                        }
                        else if(results.length <= 0) {
                            // 不存在，直接响应页面
                            viruserdata.retdata.info = "没有任何代理商/商户记录!";
                            viruserdata.retdata.success=false;

                            response.render("userinfo", viruserdata);
                        } else {
                            //存在数据将数据发到页面

                            viruserdata.retdata.info = "编辑代理商/商户";
                            viruserdata.retdata.success=true;
                            viruserdata.viruser= results[0];

                            response.render("userinfo", viruserdata);
                        }
                    });
                }

            }
        });


    }

    else if(method.toUpperCase() === "POST") {
        if(request.body.oper == "add")
        {
            var viruserinfo = RUtil.viruser(request);
            viruserinfo.username=request.body.username;
            viruserinfo.userpwd=crypto.createHash('md5').update(request.body.pwd+"").digest('hex');
            viruserinfo.phonenumber=request.body.phonenumber;
            viruserinfo.companyname=request.body.companyname;
            viruserinfo.email=request.body.email;
            viruserinfo.nickname=request.body.nickname;
            viruserinfo.roleid=request.body.roleid.split('_')[0];
            viruserinfo.expiredate = new Date(new Date().getFullYear(), new Date().getMonth()+Number(request.body.roleid.split('_')[1]), new Date().getDate());

            viruserinfo.userflag=1;
            viruserinfo.proxyid=request.session.admin.id;

            viruser.insert(viruserinfo, function(error,results) {
                if((error)!== null)
                {
                    // 数据库异常
                    var info = { status:"error",info:'添加失败：系统内部错误(错误码：'+error.errno+')' };
                    if(error.errno==1062)
                        info = { status:"error",info:'添加失败：代理商/商户用户名已经存在！)' };
                    response.send((info));
                }
                else if(results.length <= 0) {
                    // 不存在，直接响应页面
                    var info = { status:"error",info:'添加失败！' };
                    response.send( (info));
                } else {
                    //存在数据将数据发到页面
                    var info = { status:"success",info:'添加成功！' };
                    response.send( (info));
                }
            });
        }
        else if(request.body.oper == "edit")
        {

            var viruserinfo = RUtil.viruser(request);
            viruserinfo.id=request.body.id;

            viruserinfo.username=request.body.username;
            viruserinfo.userpwd=crypto.createHash('md5').update(request.body.pwd+"").digest('hex');
            viruserinfo.phonenumber=request.body.phonenumber;
            viruserinfo.companyname=request.body.companyname;
            viruserinfo.email=request.body.email;
            viruserinfo.nickname=request.body.nickname;
            viruserinfo.roleid=request.body.roleid.split('_')[0];
            viruserinfo.expiredate = new Date(new Date().getFullYear(), new Date().getMonth()+Number(request.body.roleid.split('_')[1]), new Date().getDate());

            viruserinfo.userflag=1;


            viruser.update(viruserinfo, function(error,results) {
                if((error)!== null)
                {
                    // 数据库异常
                    var info = { status:"error",info:'更新失败：系统内部错误(错误码：'+error.errno+')' };
                    if(error.errno==1062)
                        info = { status:"error",info:'更新失败：代理商/商户用户名已经存在！)' };
                    response.send((info));
                }
                else if(results.length <= 0) {
                    // 不存在，直接响应页面
                    var info = { status:"error",info:'更新失败！' };
                    response.send( (info));
                } else {
                    //存在数据将数据发到页面
                    var info = { status:"success",info:'更新成功！' };
                    response.send( (info));
                }
            });
        }
    }

};


